#!/usr/bin/perl
use Frontier::RPC2;
use HTTP::Status;
use HTTP::Daemon::SSL;
use HTTP::Response;
use Data::Dumper;
use strict;

$SIG{CHLD} = 'IGNORE';

my $rpc_decode = new Frontier::RPC2;
my $rpc_response = new HTTP::Response 200;
$rpc_response->header('Content-Type' => 'text/xml');

our $map;
do "notmac_sync_server.pl";

my $class = $ENV{INSECURE} ? "HTTP::Daemon" : "HTTP::Daemon::SSL";

my $d = $class->new(
    LocalPort => $class =~ /SSL/ ? 443 : 80,
    ReuseAddr => 1,
) or die "Couldn't bind: $!\n";

print "Please contact me at: ", $d->url, "\n";

while (1)
{
    my $c = $d->accept
	or next;

    if (fork)
    {
	$c->close($class =~ /SSL/ ? (SSL_no_shutdown => 1) : ());
	undef($c);
	next;
    }

    $d->close($class =~ /SSL/ ? (SSL_no_shutdown => 1) : ());
    undef($d);

    while (my $request = $c->get_request)
    {
	$rpc_response->content($rpc_decode->serve($request->content, $map));
	$c->send_response($rpc_response);
    }

    $c->close;
    undef($c);
    exit;
}
